package com.zrfintech.common.util;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class HttpRequestUtil {

    /**
     * 获取客户端真实IP地址
     * 
     * @param request
     * @return
     */
    public static String getRemoteRealIpAddr(HttpServletRequest request) {
        if (null == request) {
            return null;
        }
        // nginx转发设置的头
        String ip = getIpForHeader(request, "X-Real-IP");
        if (null != ip) {
            return format(ip);
        }
        ip = getIpForHeader(request, "x-forwarded-for");
        if (null != ip) {
            return format(ip);
        }
        ip = getIpForHeader(request, "Proxy-Client-IP");
        if (null != ip) {
            return format(ip);
        }
        ip = getIpForHeader(request, "WL-Proxy-Client-IP");
        if (null != ip) {
            return format(ip);
        }
        return format(request.getRemoteAddr());
    }

    private static String format(String ip) {
        if (ip == null || -1 == ip.indexOf(",")) {
            return ip;
        }
        String[] ips = StringUtils.split(ip, ",");
        for (int i = 0; i < ips.length; i++) {
            String realIP = ips[i] == null ? "" : ips[i].trim();
            if (!"unknown".equals(realIP) && !"".equals(realIP)) {
                return ip;
            }
        }
        return null;
    }

    private static String getIpForHeader(HttpServletRequest request, String headerName) {
        String ip = request.getHeader(headerName);
        if (StringUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        } else {
            return null;
        }
    }
}